package com.daykw.ip.task;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import com.daykw.ip.model.Ips;
import com.daykw.ip.util.SpringContextHolder;

@Service
public class CleanIpTask extends CustmTask {
	private static Logger logger = Logger.getLogger(CleanIpTask.class);

	@Override
	public void doStart() {

		try {
			/**
			 * 5分钟切换一次ip
			 */

			if (QuartzManager.getTrigger("CleanIpTask") == null) {
				QuartzManager.addJob("CleanIpTask", this, "0/30 * * * * ?");
			} else {
				logger.error("############已经存在任务：CleanIpTask############");
			}
		} catch (Exception e) {
			logger.error("", e);
		}

	}//

	@Override
	public void doWork() {
		try {
			if (SpringContextHolder.getApplicationContext() == null) {
				try {
					TimeUnit.SECONDS.sleep(3);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				logger.info("等待上下文启动");
			}
			//NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			NutDao bdsDao = SpringContextHolder.getBean("bdsDao");
			DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String nowtime = FORMAT.format(new Date());

			try {
				Calendar beforeTime = Calendar.getInstance();
				beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
				Date be = beforeTime.getTime();
				//int xcont = xhsDao.clear(Ips.class, Cnd.where("create_time", "<", be));
				int bcont = bdsDao.clear(Ips.class, Cnd.where("create_time", "<", be));
				logger.info("清空5分分钟之前的BDS:" + bcont + ",5分钟之前:" + FORMAT.format(be));
			} catch (Exception e) {
				logger.error("", e);
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
